define([
	"jquery",
	"bbcare",
	"bootstrap",
	"template",
	"oms_config/root",
	"oms_vm/navbar",
	"oms_tpl/application.tpl",
	"oms_model/account",
	"ac/app/applicationCache"],
	function ($, $bb, $bootstrap, $template, $root, $navbar, tpl_app, Account, $applicationCache) {
		var defaults, home = {}

		/**
		 * 获取当前登录的账号信息
		 */
		var getCurrUser = function () {
			var account = $bb.getSessionStorage("account")
			if (account == null) {
				window.location.href = "login.html?code=301"
			} else {
				account = eval("(" + account + ")")
				account = new Account(account)
			}
			return account
		}

		/**
		 * 获取菜单信息成功后的回调函数
		 */
		var getNavsCallBack = function (account) {
			// load
			$(".sidebar-lc,#content").css({ "display": "block" })
			$("#page-loading").css({ "display": "none" })
			// 这是session
			defaults.account = account
			setSession()
			//初始化导航菜单
			$navbar.init({
				navs: defaults.account.navs
			})
			workers()  // 多线程
			$applicationCache.updateCache() //更新应用缓存
		}

		/**
		 * 获取菜单信息
		 */
		var getNavs = function (data) {
			var followup = $bb.baseUrl("followup")

			// 新旧进去不同接口查询菜单
			if (data.project && data.project.projectId) {
				var params = {
					"appId": data.app.id,
					"projectId": data.project.projectId,
					"sessionID": defaults.account.sessionID,
				}
				$.post("/oms/auth/app/switchProject", params, function (ret) {
					if (ret && ret.success) {
						var account = JSON.parse($bb.getSessionStorage("account"))
						account = new Account(account, ret.data.navbars)
						getNavsCallBack(account)
					} else {
						window.location.href = "login.html"
					}
				})
			} else {

				$bb.get("/oms/auth/app/switch?appId=" + data.app.id, function (ret) {
					if (ret && ret.success) {
						$bb.setSessionStorage("account", JSON.stringify(ret.data))
						var account = new Account(ret.data)
						window.__config__.role = JSON.parse($bb.getSessionStorage("account")).role
						getNavsCallBack(account)
					} else {
						window.location.href = "login.html"
					}
				})
			}
		}

		/**
		 * 获取选中的project（或租户）的信息
		 */
		var getProject = function () {
			var apps = defaults.account.apps
			var projects = defaults.account.projects
			var data = {}
			if (projects.length > 0) {
				for (var i = 0; i < projects.length; i++) {
					if (projects[i].selectStatus == 1) {
						data.project = projects[i]
					}
				}
			}
			for (var i = 0; i < apps.length; i++) {
				if (apps[i].status == 1) {
					data.app = apps[i]
				}
			}
			// 系统名字多余11字时(即换行)
			if (data.project && data.project.projectName && data.project.projectName.length > 11) data.project.projectNameClassnName = "tenant_name_2"
			if (data.app && data.app.tenantName && data.app.tenantName.length > 11) data.app.tenantNameClassnName = "tenant_name_2"
			return data
		}

		/**
		 * 初始化账户相关信息
		 */
		var initAccount = function () {
			//初始化用户名称
			$("#oms_account_name").text(defaults.account.alias)
			//初始化最小化导航栏事件
			$(".sidebar-toggle").click(onToggleNavbar)
			//初始化登出事件
			$("#logout").click(onLogout)
			//初始化返回到全部工程页面
			$("#go-projects,.go-projects").click(onGoProjects)
			//初始化当前账号菜单栏
			$('.dropdown-toggle').dropdown()
			//若只有一个租户并且该租户下没有项目或者只有一个项目时
			if (defaults.account.apps.length == 1 && (!defaults.account.apps[0].auProjectRoleRel || defaults.account.apps[0].auProjectRoleRel.length == 1)) {
				$(".go-projects").css({ "display": "none" })
				$("#go-projects").parent("li").css({ "display": "none" })
			}
			setSession()
		}

		/**
		 * 初始化全局UI
		 */
		var initUI = function () {
			// load
			$(".sidebar-lc,#content").css({ "display": "none" })
			$("#page-loading").css({ "display": "block" })
			// 初始化账户相关信息
			initAccount()
			// 初始化应用列表
			var data = getProject() //获取选中的project（或租户）的信息
			tpl_app.init('bb-tenant')
			$('#bb-tenant').html($template("tpl_application_dropdown", data))
			// 请求菜单信息
			getNavs(data)
		}

		/**
		 * 最小化(恢复)导航栏
		 */
		var onToggleNavbar = function () {
			$("#bb-tenant").toggleClass("mini")
			$(".sidebar-lc").toggleClass("mini")
			$("#content").toggleClass("max")
		}

		/**
		 * 退出系统处理
		 */
		var onLogout = function () {
			var config = $root.init()
			window.location.href = config.route.login
		}

		/**
		 * 返回到全部工程页面
		 */
		var onGoProjects = function () {
			window.location.href = "projects.html"
		}

		/**
		 * 设置Session
		 */
		var setSession = function () {
			$bb.setSessionStorage("sessionId", defaults.account.sessionID)
			$bb.setSessionStorage("sessionTime", new Date().getTime())
		}

		/**
		 * 版本控制
		 * new menu 和 old menu 比较
		 * 减少了menu 或 resourceList里的templId 就清除对应的IocalStorage
		 * 添加menu 或 resourceList里的templId 或 修改了resourceList里的templVersion
		 */
		// 删除
		var removeItemLocalStorage = function (oldData, newData) {
			for (var i = 0; i < oldData.length; i++) {
				var flagA = false
				for (var j = 0; j < newData.length; j++) {
					if (oldData[i].menuId == newData[j].menuId) {
						flagA = true
						for (var p = 0; p < oldData[i].resourceList.length; p++) {
							var flagB = false
							for (var q = 0; q < newData[j].resourceList.length; q++) {
								if (oldData[i].resourceList[p].templId == newData[j].resourceList[q].templId) {
									var flagB = true
								}
							}
							if (!flagB) { // del task
								localStorage.removeItem("templId" + oldData[i].resourceList[p].templId)
							}
						}
					}
				}
				if (!flagA) { // del nav
					for (var k = 0; k < oldData[i].resourceList.length; k++) {
						localStorage.removeItem("templId" + oldData[i].resourceList[k].templId)
					}
				}
			}
		}
		// 为了方便多次使用 封装参数
		var pushArr = function (resource, arr) {
			var params = {}
			params.templId = resource.templId
			params.templVersion = resource.templVersion
			arr.push(params)
		}
		// 添加、修改 (将添加和修改的参数放入arr)
		var modifyItemLocalStorage = function (oldData, newData) {
			var arr = []
			for (var i = 0; i < newData.length; i++) {
				var flagA = false
				for (var j = 0; j < oldData.length; j++) {
					if (newData[i].menuId == oldData[j].menuId) {
						flagA = true
						for (var p = 0; p < newData[i].resourceList.length; p++) {
							var flagB = false
							for (var q = 0; q < oldData[j].resourceList.length; q++) {
								if (newData[i].resourceList[p].templId == oldData[j].resourceList[q].templId) {
									var flagB = true
									if (newData[i].resourceList[p].templVersion != oldData[j].resourceList[q].templVersion) {
										pushArr(newData[i].resourceList[p], arr)
									}
								}
							}
							if (!flagB) { // add task
								pushArr(newData[i].resourceList[p], arr)
							}
						}
					}
				}
				if (!flagA) { // add nav
					for (var k = 0; k < newData[i].resourceList.length; k++) {
						pushArr(newData[i].resourceList[k], arr)
					}
				}
			}
			return arr
		}
		var controlSvn = function (oldData, newData) {
			removeItemLocalStorage(oldData, newData)
			return modifyItemLocalStorage(oldData, newData)
		}
		var controlSvnFirst = function (newData) {
			var arr = []
			for (var i = 0; i < newData.length; i++) {
				for (var k = 0; k < newData[i].resourceList.length; k++) {
					pushArr(newData[i].resourceList[k], arr)
				}
			}
			return arr
		}
		// 将离线nav里的resourceList数组清空，(第一次)
		var emptyResourceList = function (data) {
			var newNavHandle = []
			$.each(data, function (i, obj1) {
				var objA = {}
				$.each(obj1, function (key1, val1) {
					if (key1 == 'menuList') {
						objA[key1] = []
						$.each(val1, function (j, obj2) {
							var objB = {}
							$.each(obj2, function (key2, val2) {
								if (key2 == "resourceList") {
									objB[key2] = []
								} else {
									objB[key2] = val2
								}
							})
							objA[key1].push(objB)
						})
					} else {
						objA[key1] = val1
					}
				})
				newNavHandle.push(objA)
			})
			return newNavHandle
		}
		// 获得更新后的模板集合
		var getUpdateTempl = function (data) {
			var updateTemplArr = JSON.parse($bb.getIocalStorage("updateTemplArr"))
			if (updateTemplArr == null) updateTemplArr = []
			if (updateTemplArr.length > 0) {
				for (var i = 0; i < updateTemplArr.length; i++) {
					if (updateTemplArr[i].templId == data.templId) {
						updateTemplArr.splice(i, 1)
					}
				}
			}
			updateTemplArr.push(data)
			$bb.setIocalStorage("updateTemplArr", JSON.stringify(updateTemplArr))
			return updateTemplArr
		}
		// 获得更新后的nav
		var getUpdateNav = function (updateTemplArr) {
			var newNav = JSON.parse($bb.getSessionStorage("cacheNav"))
			var newNavUpdate = []
			$.each(newNav, function (i, obj1) {
				var objA = {}
				$.each(obj1, function (key1, val1) {
					if (key1 == 'menuList') {
						objA[key1] = []
						$.each(val1, function (j, obj2) {
							var objB = {}
							$.each(obj2, function (key2, val2) {
								if (key2 == "resourceList") {
									objB[key2] = []
									$.each(val2, function (k, obj3) {
										for (var p = 0; p < updateTemplArr.length; p++) {
											if (updateTemplArr[p].templId == obj3.templId && obj3.templVersion == updateTemplArr[p].templVersion) {
												var objC = {}
												$.each(obj3, function (key3, val3) {
													objC[key3] = val3
												})
												objB[key2].push(objC)
											}
										}
									})
								} else {
									objB[key2] = val2
								}
							})
							objA[key1].push(objB)
						})
					} else {
						objA[key1] = val1
					}
				})
				newNavUpdate.push(objA)
			})
			return newNavUpdate
		}

		/**
		 * 多线程开始
		 */
		var startWorker = function () {
			var w
			if (typeof (Worker) !== "undefined") {
				if (typeof (w) == "undefined") {
					w = new Worker("scprit/applicationCache/app/workers.js")
				}
				var URL = $bb.baseUrl("followup")
				$.extend(defaults.account, { "URL": URL })
				w.postMessage(JSON.stringify(defaults.account))
				w.onmessage = function (event) {
					var data = JSON.parse(event.data)
					var cacheNav = JSON.parse($bb.getIocalStorage("cacheNav"))
					if (jQuery.isArray(data)) {
						$bb.setSessionStorage("cacheNav", JSON.stringify(data))// 暂时保存在session里
						if (!cacheNav && data.length > 0) {
							var arrTempl = controlSvnFirst(data[0].menuList)
							w.postMessage(JSON.stringify({
								"sessionID": defaults.account.sessionID,
								"URL": URL,
								"arrTempl": arrTempl
							}))
							// 将离线nav里的resourceList数组清空，(第一次)
							var offlineData = {
								"alias": defaults.account.alias,
								"apps": emptyResourceList(data)
							}
							$bb.setIocalStorage("cacheNav", JSON.stringify(offlineData))
						} else if (cacheNav && data && cacheNav.apps.length > 0 && data.length > 0) {
							var oldData = cacheNav.apps[0].menuList
							var newData = data[0].menuList
							var arrTempl = controlSvn(oldData, newData)
							if (arrTempl.length > 0) {
								w.postMessage(JSON.stringify({
									"sessionID": defaults.account.sessionID,
									"URL": URL,
									"arrTempl": arrTempl
								}))
							}
						}
					} else if (data.questiones) {
						$bb.setIocalStorage("templId" + data.templId, JSON.stringify(data))
						var updateTemplArr = getUpdateTempl(data) // updateTemplArr: 每次更新后的模板集合
						var newNavUpdate = getUpdateNav(updateTemplArr) // newNavUpdate: 每次更新后的nav
						var offlineData = {
							"alias": defaults.account.alias,
							"apps": newNavUpdate
						}
						$bb.setIocalStorage("cacheNav", JSON.stringify(offlineData))
					}
				}
			} else {
				$bb.toastShow("该浏览器不支持web workers")
			}
		}

		/**
		 * 多线程
		 */
		var workers = function () {
			startWorker()
		}

		/**
		 * 初始化方案
		 */
		home.init = function () {
			defaults = {
				account: getCurrUser()
			}
			initUI()
		}

		return home
	})